package com.config;

import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.Advisor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor;
import org.springframework.security.authorization.method.PreAuthorizeAuthorizationManager;
import org.springframework.stereotype.Controller;

@Configuration
public class AuthorizationMethodInterceptorConfig {

    /**
     * 借助 CGLib 代理 controller
     * resource server 依据用户授予的权限进行访问控制
     * @return
     */
    @Bean
    public Advisor authorizationMethodInterceptor() {
        Pointcut pointcut = new AnnotationMatchingPointcut(Controller.class, PreAuthorize.class, true);

        return new AuthorizationManagerBeforeMethodInterceptor(
                pointcut, authorizationManager()
        );
    }

    @Bean
    public AuthorizationManager<MethodInvocation> authorizationManager() {


        return new PreAuthorizeAuthorizationManager();
    }

}
